package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.website.annotion.RequireLogin;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CheckLoginInterceptor implements HandlerInterceptor {
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
 /*       //获取token
      String token=  CookieUtil.getToken(response,request);
        //通过token 查redis
    UserInfo user= userInfoRedisService.getUserByToken(token);
        //判断用户是否存在
        if(user==null){
            response.sendRedirect("/login.html");
            return  false;
        }
        return  true;
    }*/
        String token = CookieUtil.getToken(response, request);

        UserInfo user = userInfoRedisService.getUserByToken(token);

        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;

            if (hm.hasMethodAnnotation(RequireLogin.class)) {

                if (user == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }

        request.getSession().setAttribute("userInfo", user);
        return true;
    }
}